<template>
	<el-dialog title="重置密码" :visible.sync="showChangePwd" :before-close="cancelPwd">
		<el-form :model="userInfo" status-icon :rules="pwdRules" ref="pwdForm" label-width="100px">
			<el-form-item label="新密码" prop="pass">
				<el-input type="password" v-model="userInfo.pass" autocomplete="off" show-password></el-input>
			</el-form-item>
			<el-form-item label="确认新密码" prop="checkPass">
				<el-input type="password" v-model="userInfo.checkPass" autocomplete="off" show-password></el-input>
			</el-form-item>
		</el-form>
		<div class="btns">
			<el-button @click="cancelPwd">取消</el-button>
			<el-button @click="changePwd" type="primary">确认</el-button>
		</div>
	</el-dialog>
</template>

<script>
import { updateAccountInfo } from '../../../api/api';
import { validatePass, validatePassChecked } from '@/utils/formValidate';

export default {
	components: {},
	props: {
		show: {
			type: Boolean,
			default: false
		},
		userId: {
			type: String,
			default: ''
		}
	},
	data() {
		return {
			userInfo: {
				userId: '',
				pass: '',
				checkPass: ''
			},

			pwdRules: {
				pass: [
					{ required: true, message: '请输入用户密码', trigger: ['blur', 'change'] },
					{ validator: validatePass, trigger: ['blur', 'change'] }
				],
				checkPass: [
					{ required: true, message: '请输入用户密码', trigger: ['blur', 'change'] },
					{ validator: validatePassChecked, trigger: ['blur', 'change'] }
				]
			},
			showChangePwd: false
		};
	},
	watch: {
		show(newVal) {
			this.showChangePwd = newVal;
		},
		userId(newVal) {
			this.userInfo.userId = newVal;
		}
	},
	computed: {},
	mounted() {},
	methods: {
		cancelPwd() {
			this.showChangePwd = false;
			this.userInfo.pass = '';
			this.userInfo.checkPass = '';
			this.validatePwd = false;
			this.$refs.pwdForm.resetFields();
			this.$emit('close');
		},
		changePwd() {
			this.$refs['pwdForm'].validate(valid => {
				if (valid) {
					const params = [
						{ op: 'replace', path: '/pwd', value: this.userInfo.pass } // 设置该用户是否失效   Y/失效  N/没有失效
					];
					const data = {};
					data.params = params;
					data.userId = this.userInfo.userId;
					updateAccountInfo(data)
						.then(() => {
							this.$message.success('重置密码成功！');
							this.$emit('close');
							this.showChangePwd = false;
							this.$refs.pwdForm.resetFields();
						})
						.catch(err => {
							this.$Spin.hide();
							this.$requestApiError(err, () => {
								this.$router.push('/');
							});
						});
				}
			});
		}
	}
};
</script>

<style lang="less">
.account {
	.btns {
		text-align: right;
	}
	.head {
		padding: 20px 0;
	}
	.el-avatar > img {
		width: 100%;
	}
}
</style>
